﻿namespace EFS.RC.SupervisorCentral.Controls.Agents.Search
{
	public partial class AD : EFS.RC.SupervisorCentral.Controls.Control
	{
		#region Delegates
		public delegate void UserSelectedDelegate(EFS.AD.User user);
		public UserSelectedDelegate OnUserSelected = null;
		#endregion

		#region Locals
		/// modalHostParent
		private EFS.Common.UI.Controls.ModalDialogHost modalHostParent = null;
		#endregion

		#region Constructors
		/// Implicit
		public AD()
		{
			InitializeComponent();

			ConstructorNotAllowed();
		}

		/// Explicit
		public AD(
			EFS.Common.UI.Controls.ModalDialogHost modalHostParent)
		{
			InitializeComponent();

			// ignore in designer
			if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
			{
				// set
				this.modalHostParent = modalHostParent;
				this.modalHostParent.OnButtonOKClick += OnParentOKClicked;
			}

		}
		#endregion

		#region Properties
		/// Property IsValid: Get
		public System.Boolean? IsValid
		{
			get
			{
				return null != SelectedUser;
			}
		}

		/// Property SelectedUser: Get
		public EFS.AD.User SelectedUser
		{
			get
			{
				return (EFS.AD.User)listViewSurveys.SelectedItem;
			}
		}

		/// Property IsValid: Get
		private System.String SearchText
		{
			get
			{
				return EFS.Common.Functions.String.GetLowerTrimmedString(textBoxName.Text);
			}
		}
		#endregion

		#region Utilities
		/// OKClicked
		private void OKClicked()
		{
			// test if valid
			if (IsValid.HasValue && !IsValid.Value)
			{
				ShowErrorMessage("Please select an agent");
				return;
			}

			// close parent
			this.modalHostParent.Close(EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok);

			// call registered delegates
			if (null != OnUserSelected)
			{
				OnUserSelected(SelectedUser);
			}
		}
		#endregion

		#region Events
		/// Loaded
		private void Control_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			textBoxName.Focus();
		}

		/// OnParentOKClicked
		private void OnParentOKClicked(object sender, System.Windows.RoutedEventArgs e, System.Boolean dialogResult)
		{
			OKClicked();
		}

		/// TextBox change
		private void textBoxName_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
		{
			// only if more than 3 chars
			if (!EFS.Common.Verify.String(SearchText) || SearchText.Length < 3)
			{
				return;
			}

			// clear list
			listViewSurveys.ItemsSource = EFS.RC.SupervisorCentral.Common.Session.Instance.Domain.Filter(null, true, SearchText, false);
			if (1 == listViewSurveys.Items.Count)
			{
				listViewSurveys.SelectedIndex = 0;
			}
		}

		/// textBoxName_KeyDown
		private void textBoxName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == System.Windows.Input.Key.Enter)
			{
				OKClicked();
			}
		}
		#endregion
	}

}